package com.common.manager.net.asynchttp;

import android.content.Context;

import com.common.utility.Logger;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;


public abstract class ProjectAsyncHttpResponseHandler extends AsyncHttpResponseHandler {
	
	private final static String TAG = "ProjectAsyncHttpResponseHandler";
	
	private String url;
	private Context context;
	private boolean willCache;

    private static final String CODE_KEY = "returncode";
    private static final int OK_CODE = 100;
	
	public ProjectAsyncHttpResponseHandler(Context context,String url,boolean cache){
		this.url = url;
		this.context = context;
		willCache = cache;
	}

    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
        String content = new String(responseBody);
        Logger.e("success statusCode:"+statusCode+";content:"+content);
        switch (statusCode){
            case 200:
                try {
                    JSONObject jsonObject = new JSONObject(content);
                    if(jsonObject.optInt(CODE_KEY) == OK_CODE){
                        //TODO cache data
                        parseContent(content);
                    }else{
                        onFailure(statusCode,headers,responseBody,new Exception(jsonObject.optString("returnmessage")));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }


                break;
        }
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
        String content = "";
        if(responseBody != null){
            content = new String(responseBody);
        }

        Logger.e("error statusCode:"+statusCode+";content:"+content+";error:"+error.getMessage());
        error.printStackTrace();
    }

    public void onSuccess(String content){

    }

    public void onParseContentFailure(Exception e) {
		this.showDialog("数据错误");
	}
	
	private void showDialog(String msg){

		
	}
	
	protected abstract void parseContent(String content);
	protected void parseOnFailure(){};
}
